package mysql

import (
	model "argus_go_server/Model"
	"fmt"
	"os"
	"path/filepath"

	"github.com/go-ini/ini"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB
var cfg *ini.File
var DbaseSocure string

// 加载数据库参数
func loadDatabaseConfig() {
	// 获取当前路径
	wd, _ := os.Getwd()
	configPath := filepath.Join(wd, "conf", "app.ini")

	var err error
	cfg, err = ini.Load(configPath)
	if err != nil {
		panic(err)
	}
	db_name := cfg.Section("database").Key("DATABASE").String()
	db_host := cfg.Section("database").Key("HOST").String()
	db_port := cfg.Section("database").Key("PORT").String()
	db_user := cfg.Section("database").Key("USER").String()
	db_password := cfg.Section("database").Key("PASSWORD").String()
	charset := cfg.Section("database").Key("CHARSET").String()
	DbaseSocure = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local", db_user, db_password, db_host, db_port, db_name, charset)
	DB, err = gorm.Open(mysql.Open(DbaseSocure), &gorm.Config{})
	if err != nil {
		panic("数据库连接失败")
	} else {
		fmt.Println("数据库连接成功")
		models := []interface{}{
			&model.User{},
		}
		for _, model := range models {
			if err := DB.AutoMigrate(model); err != nil {
				fmt.Printf("数据库迁移失败: %v\n", err)
			}
		}
	}
}
func init() {
	loadDatabaseConfig()
}
